<?php

class Action_User_Socialuser extends Action
{
	function execute($request)
	{
		$data = null;

		if ($request -> isPost())
		{
			$service = $request -> getParam('service');

			$json = $request -> getParam('json');

			$data = json_decode(urldecode($json), 1);

		}

		$email = null;

		if ($data)
		{
			$email = $data['email'];
			$service = $data['idp_service'];

			$id = $data['idp_id'];

			// check if user with existing data is exist or not.

			$_id = $service . '.' . $id;

			$socialuser = Document::factory('socialuser', $_id);

			if (!$socialuser -> load())
			{
				$socialuser -> _id = $_id;
				$socialuser -> idp_id = $id;
				$socialuser -> idp_service = $service;
				$socialuser -> email = $email;
				$socialuser -> name = $data['name'];
				$socialuser -> birthday = $data['birthday'];
				$socialuser -> profile_url = $data['profile_url'];
				$socialuser -> profile_image_url = $data['profile_image_url'];
				$socialuser -> gender = $data['gender'];

				$socialuser -> save();

				Agilet::redirect('/user/connect', array('idp' => $_id));
			}

			if ($socialuser -> user_id)
			{
				$id = intval($socialuser -> user_id);

				$user = Document::factory('user', $id);

				if ($user -> load())
				{
					$user -> login();

					Agilet::redirect('/');
				}
				else
				{
					$socialuser -> user_id = 0;
					$socialuser -> save();
				}
			}

			// check if email exists

			$db = Document::factory('user') -> collection();

			$email = $db -> findOne(array('email' => $email));

			Agilet::redirect('/user/connect', array('idp' => $_id));
		}
	}

}
